<template>
  <div class="login-background">
    <div class="login-container">
      <div class="login-title">欢迎登录</div>
      <!-- 根据当前登录方式动态渲染 -->
      <el-form v-if="loginType === 'password'" ref="form" :model="form" size="normal" :rules="rules" @submit.native.prevent="handleLogin">
        <!-- 用户名和密码输入项 -->
        <el-form-item prop="userId">
          <el-input
              prefix-icon="el-icon-user"
              v-model="form.userId"
              placeholder="请输入用户id"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              prefix-icon="el-icon-key"
              type="password"
              v-model="form.password"
              show-password
              placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
              style="width: 100%; text-align: center"
              type="primary"
              native-type="submit"
          >
            登 录
          </el-button>
        </el-form-item>
      </el-form>
      <div v-else-if="loginType === 'qrCode'" class="qr-code-container">
        <canvas id="qrCodeCanvas" v-show="qrCodeContent"></canvas> <!-- 根据qrCodeContent控制显示 -->
        <p v-show="!qrCodeContent">正在加载二维码...</p> <!-- 当qrCodeContent为空时显示 -->
      </div>
      <div style="text-align: center; margin-top: 20px;">
        <el-button type="text" @click="switchLoginType('password')" v-if="loginType !== 'password'">使用密码登录</el-button>
        <el-button type="text" @click="switchLoginType('qrCode')" v-else>使用微信扫码登录</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import requestUtil from "../network/request";
import Cookie from "js-cookie";
import QRCode from 'qrcode';
import {mapState} from "vuex";

export default {
  name: "LoginPage",
  data() {
    return {
      loginType: 'password', // 默认登录方式
      form: {
        userId: '',
        password: ''
      },
      qrCodeContent: null, // 存储二维码的内容
      rules: {
        userId: [
          { required: true, message: "请输入用户id", trigger: "blur" },
          { min: 1, max: 20, message: "用户id过长", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 1, max: 20, message: "密码过长", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    ...mapState('websocket', ['ws']), // 假设websocket模块已正确配置，并且ws实例存储在state中
  },
  methods: {
    handleLogin() {
      this.login();
    },
    login() {
      if(this.loginType === 'password') {
        this.$refs.form.validate((valid) => {
          if (valid) {
            requestUtil.post("/login", this.form).then((res) => {
              if (res.code === "0") {
                const userId = res.result.userId;
                const token = res.result.token;
                // 将用户token信息存到cookie中
                const expireTime = 24 * 60 * 60; // 24小时有效期
                const expirationDate = new Date();
                expirationDate.setTime(expirationDate.getTime() + expireTime * 1000); // 注意：时间单位是毫秒

                Cookie.set("token", token, { expires: expirationDate });
                Cookie.set("userId", userId, { expires: expirationDate });
                this.getUserInfo().then(() => {
                  this.$router.push("/home"); // 登录成功后跳转到主页
                });
              } else {
                this.$message({
                  type: "error",
                  message: res.msg,
                });
              }
            }).catch(error => {
              console.error('Error during login:', error);
              this.$message.error('网络错误，请稍后再试');
            });
          }
        });
      } else {
        // 扫码登录逻辑可以在此处进一步扩展
      }
    },
    switchLoginType(type) {
      this.loginType = type;
      if(type === 'qrCode') {
        this.fetchQrCodeViaWebSocket();
      }
    },
    fetchQrCodeViaWebSocket() {
      const ws = this.ws; // 获取WebSocket实例
      if(ws && ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({"type": 1})); // 发送消息给服务端

        // 监听消息事件，等待服务器返回二维码内容
        ws.onmessage = (event) => {
          const response = JSON.parse(event.data);
          // 处理返回的微信登录二维码
          if(response.type === 1) {
            this.qrCodeContent = response.data.loginUrl;
            this.generateQRCode();
          }
          // 处理登录成功的响应
          else if(response.type === 3) {
            const userId = response.data.userId;
            const token = response.data.token;
            const nickName = response.data.nickName;

            // 将用户token信息存到cookie中
            const expireTime = 24 * 60 * 60; // 24小时有效期
            const expirationDate = new Date();
            expirationDate.setTime(expirationDate.getTime() + expireTime * 1000); // 注意：时间单位是毫秒

            Cookie.set("token", token, { expires: expirationDate });
            Cookie.set("userId", userId, { expires: expirationDate });
            Cookie.set("nickName", nickName, { expires: expirationDate });

            // 获取用户信息并跳转至首页
            this.getUserInfo().then(() => {
              this.$router.push("/home"); // 登录成功后跳转到主页
            }).catch(error => {
              console.error('Error fetching user info:', error);
              this.$message.error('获取用户信息失败，请稍后再试');
            });
          }
        };
      } else {
        this.$message.error('连接服务器失败...');
      }
    },
    generateQRCode() {
      const canvas = document.getElementById('qrCodeCanvas');
      if (this.qrCodeContent && canvas) {
        QRCode.toCanvas(canvas, this.qrCodeContent, function (error) {
          if (error) console.error(error)
          console.log('QR Code generated successfully!');
        })
      }
    },
    getUserInfo() {
      return requestUtil.post('/user/info/query', {
        userId: Cookie.get("userId")
      }).then((res) => {
            if (res.code === "0") {
              const nickName = res.result.nickName;
              const expireTime = 2 * 60 * 60; // 两小时有效期
              const expirationDate = new Date();
              expirationDate.setDate(expirationDate.getTime() + expireTime);
              Cookie.set("nickName", res.result.nickName, { expires: expirationDate });
              this.$message({
                message: "欢迎回来，" + nickName,
                type: 'success',
                duration: 1000,
              });
            } else {
              throw new Error(res.msg || '获取用户信息失败');
            }
          });
    }
  }
};
</script>

<style lang="less" scoped>
.login-background {
  width: 100%;
  height: 100vh;
  background-color: darkslateblue;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center; /* 确保容器垂直居中 */
}

.login-container {
  width: 400px;
  background: rgba(255, 255, 255, 0.8); /* 可选：增加背景色以提高可读性 */
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);

  .login-title {
    color: black;
    font-size: 30px;
    text-align: center;
    margin-bottom: 20px;
  }

  .qr-code-container {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column; /* 确保文本也在二维码下方居中 */
  }

  #qrCodeCanvas {
    margin-bottom: 10px; /* 给二维码下方留一些空间 */
  }
}
</style>